import { useState, useEffect } from 'react';
import { Search, Save, CheckCircle, Settings, Cpu, Info, ToggleLeft, ToggleRight, RefreshCw, PlusCircle, X, HelpCircle, Folder, Download } from 'lucide-react';
import { updateService } from '@/lib/updateService';
import { open } from '@tauri-apps/plugin-dialog';

// 模型配置组件
function ModelConfigSection() {
  const [selectedModel, setSelectedModel] = useState('ollama');
  const [searchQuery, setSearchQuery] = useState('');
  const [modelStatus, setModelStatus] = useState<Record<string, boolean>>({
    ollama: true,
    openai: false,
    gemini: false,
    lmstudio: false,
    custom: false
  });

  // 模型配置状态
  const [ollamaConfig, setOllamaConfig] = useState({ baseUrl: 'http://localhost:11434', model: 'llama3', models: ['llama3', 'qwen2:7b', 'mistral', 'gemma:7b'] });
  const [openAIConfig, setOpenAIConfig] = useState({ apiKey: '', baseUrl: 'https://api.openai.com/v1', model: 'gpt-3.5-turbo' });
  const [geminiConfig, setGeminiConfig] = useState({ apiKey: '', baseUrl: 'https://generativelanguage.googleapis.com', model: 'gemini-pro' });
  const [lmStudioConfig, setLMStudioConfig] = useState({ baseUrl: 'http://localhost:1234/v1', model: '' });
  const [customConfig, setCustomConfig] = useState({ baseUrl: '', apiKey: '', model: '' });
  const [isSearchFocused, setIsSearchFocused] = useState(false);
  const [isLoadingModels, setIsLoadingModels] = useState(false);

  // 从localStorage加载配置
  useEffect(() => {
    const savedConfigs = localStorage.getItem('modelConfigs');
    const savedStatus = localStorage.getItem('modelStatus');
    if (savedConfigs) {
      const configs = JSON.parse(savedConfigs);
      if (configs.ollama) setOllamaConfig(configs.ollama);
      if (configs.openai) setOpenAIConfig(configs.openai);
      if (configs.gemini) setGeminiConfig(configs.gemini);
      if (configs.lmstudio) setLMStudioConfig(configs.lmstudio);
      if (configs.custom) setCustomConfig(configs.custom);
    }
    if (savedStatus) {
      setModelStatus(JSON.parse(savedStatus));
    }
  }, []);

  const saveModelConfigs = () => {
    const configs = {
      ollama: ollamaConfig,
      openai: openAIConfig,
      gemini: geminiConfig,
      lmstudio: lmStudioConfig,
      custom: customConfig
    };
    localStorage.setItem('modelConfigs', JSON.stringify(configs));
    localStorage.setItem('modelStatus', JSON.stringify(modelStatus));
    alert('模型配置已保存');
  };

  const toggleModelStatus = (model: string) => {
    const newStatus = {...modelStatus};
    newStatus[model] = !newStatus[model];
    setModelStatus(newStatus);
    // 如果启用了新模型，自动选择它
    if (newStatus[model]) {
      setSelectedModel(model);
    }
  };

  const fetchOllamaModels = async () => {
    if (!modelStatus.ollama) return;
    setIsLoadingModels(true);
    try {
      const response = await fetch(`${ollamaConfig.baseUrl}/api/tags`);
      if (response.ok) {
        const data = await response.json();
        if (data.models && data.models.length > 0) {
          setOllamaConfig(prev => ({
            ...prev,
            models: data.models.map((m: any) => m.name)
          }));
          // 如果当前模型不在列表中，选择第一个模型
          if (!data.models.some((m: any) => m.name === ollamaConfig.model)) {
            setOllamaConfig(prev => ({
              ...prev,
              model: data.models[0]?.name || ''
            }));
          }
        }
      }
    } catch (error) {
      console.error('Failed to fetch Ollama models:', error);
    } finally {
      setIsLoadingModels(false);
    }
  };

  const filteredModels = [
    { id: 'ollama', name: 'Ollama', icon: <Cpu className="h-4 w-4" />, status: modelStatus.ollama },
    { id: 'openai', name: 'OpenAI', icon: <RefreshCw className="h-4 w-4" />, status: modelStatus.openai },
    { id: 'gemini', name: 'Gemini', icon: <RefreshCw className="h-4 w-4" />, status: modelStatus.gemini },
    { id: 'lmstudio', name: 'LM Studio', icon: <Cpu className="h-4 w-4" />, status: modelStatus.lmstudio },
    { id: 'custom', name: '自定义模型', icon: <PlusCircle className="h-4 w-4" />, status: modelStatus.custom },
  ].filter(model => 
    model.name.toLowerCase().includes(searchQuery.toLowerCase())
  );

  // 渲染模型配置表单
  const renderModelConfig = () => {
    switch(selectedModel) {
      case 'ollama':
        return (
          <div className="space-y-6 p-6 bg-white rounded-xl shadow-sm border border-gray-100">
            <div className="flex justify-between items-center">
              <h3 className="text-lg font-semibold text-gray-800">Ollama 配置</h3>
              <button
                onClick={fetchOllamaModels}
                disabled={isLoadingModels}
                className="text-sm text-blue-600 flex items-center hover:text-blue-800"
              >
                {isLoadingModels ? (
                  <RefreshCw className="h-4 w-4 mr-1 animate-spin" />
                ) : (
                  <RefreshCw className="h-4 w-4 mr-1" />
                )}
                刷新模型
              </button>
            </div>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Base URL</label>
                <input
                  type="text"
                  value={ollamaConfig.baseUrl}
                  onChange={(e) => setOllamaConfig({...ollamaConfig, baseUrl: e.target.value})}
                  className="w-full px-3 py-2.5 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  placeholder="http://localhost:11434"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">模型</label>
                <div className="relative">
                  <select
                    value={ollamaConfig.model}
                    onChange={(e) => setOllamaConfig({...ollamaConfig, model: e.target.value})}
                    className="w-full px-3 py-2.5 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 appearance-none bg-white"
                  >
                    {ollamaConfig.models.map(model => (
                      <option key={model} value={model}>{model}</option>
                    ))}
                  </select>
                  <div className="absolute inset-y-0 right-0 flex items-center px-2 pointer-events-none text-gray-500">
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 9l-7 7-7-7"></path>
                    </svg>
                  </div>
                </div>
                <p className="mt-1 text-xs text-gray-500">确保模型已在Ollama中安装</p>
              </div>
            </div>
          </div>
        );
      case 'openai':
        return (
          <div className="space-y-4 p-6 bg-white rounded-xl shadow-sm border border-gray-100">
            <h3 className="text-lg font-semibold text-gray-800 mb-4">OpenAI 配置</h3>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">API Key</label>
                <input
                  type="password"
                  value={openAIConfig.apiKey}
                  onChange={(e) => setOpenAIConfig({...openAIConfig, apiKey: e.target.value})}
                  className="w-full px-3 py-2.5 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  placeholder="sk-...your-openai-api-key"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Base URL</label>
                <input
                  type="text"
                  value={openAIConfig.baseUrl}
                  onChange={(e) => setOpenAIConfig({...openAIConfig, baseUrl: e.target.value})}
                  className="w-full px-3 py-2.5 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  placeholder="https://api.openai.com/v1"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">模型名称</label>
                <input
                  type="text"
                  value={openAIConfig.model}
                  onChange={(e) => setOpenAIConfig({...openAIConfig, model: e.target.value})}
                  className="w-full px-3 py-2.5 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  placeholder="gpt-3.5-turbo"
                />
              </div>
            </div>
          </div>
        );
      case 'gemini':
        return (
          <div className="space-y-4 p-6 bg-white rounded-xl shadow-sm border border-gray-100">
            <h3 className="text-lg font-semibold text-gray-800 mb-4">Gemini 配置</h3>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">API Key</label>
                <input
                  type="password"
                  value={geminiConfig.apiKey}
                  onChange={(e) => setGeminiConfig({...geminiConfig, apiKey: e.target.value})}
                  className="w-full px-3 py-2.5 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  placeholder="your-gemini-api-key"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Base URL</label>
                <input
                  type="text"
                  value={geminiConfig.baseUrl}
                  onChange={(e) => setGeminiConfig({...geminiConfig, baseUrl: e.target.value})}
                  className="w-full px-3 py-2.5 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  placeholder="https://generativelanguage.googleapis.com"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">模型名称</label>
                <input
                  type="text"
                  value={geminiConfig.model}
                  onChange={(e) => setGeminiConfig({...geminiConfig, model: e.target.value})}
                  className="w-full px-3 py-2.5 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  placeholder="gemini-pro"
                />
              </div>
            </div>
          </div>
        );
      case 'lmstudio':
        return (
          <div className="space-y-4 p-6 bg-white rounded-xl shadow-sm border border-gray-100">
            <h3 className="text-lg font-semibold text-gray-800 mb-4">LM Studio 配置</h3>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Base URL</label>
                <input
                  type="text"
                  value={lmStudioConfig.baseUrl}
                  onChange={(e) => setLMStudioConfig({...lmStudioConfig, baseUrl: e.target.value})}
                  className="w-full px-3 py-2.5 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  placeholder="http://localhost:1234/v1"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">模型名称</label>
                <input
                  type="text"
                  value={lmStudioConfig.model}
                  onChange={(e) => setLMStudioConfig({...lmStudioConfig, model: e.target.value})}
                  className="w-full px-3 py-2.5 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  placeholder="your-local-model"
                />
              </div>
            </div>
          </div>
        );
      case 'custom':
        return (
          <div className="space-y-4 p-6 bg-white rounded-xl shadow-sm border border-gray-100">
            <h3 className="text-lg font-semibold text-gray-800 mb-4">自定义模型配置</h3>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Base URL</label>
                <input
                  type="text"
                  value={customConfig.baseUrl}
                  onChange={(e) => setCustomConfig({...customConfig, baseUrl: e.target.value})}
                  className="w-full px-3 py-2.5 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  placeholder="https://your-custom-api.com/v1"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">API Key</label>
                <input
                  type="password"
                  value={customConfig.apiKey}
                  onChange={(e) => setCustomConfig({...customConfig, apiKey: e.target.value})}
                  className="w-full px-3 py-2.5 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  placeholder="your-api-key"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">模型名称</label>
                <input
                  type="text"
                  value={customConfig.model}
                  onChange={(e) => setCustomConfig({...customConfig, model: e.target.value})}
                  className="w-full px-3 py-2.5 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  placeholder="your-model-name"
                />
              </div>
            </div>
          </div>
        );
      default:
        return null;
    }
  };

  return (
    <div className="bg-white rounded-xl shadow-md p-0 overflow-hidden border border-gray-100">
      <div className="flex flex-col md:flex-row">
        {/* 左侧模型列表 */}
        <div className="w-full md:w-72 border-b md:border-b-0 md:border-r border-gray-200 bg-gray-50">
          <div className="p-4 border-b border-gray-200 bg-white">
            <div className={`relative ${isSearchFocused ? 'ring-2 ring-blue-500' : ''} rounded-lg overflow-hidden`}>
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
              <input
                type="text"
                placeholder="搜索模型..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                onFocus={() => setIsSearchFocused(true)}
                onBlur={() => setIsSearchFocused(false)}
                className="w-full pl-10 pr-4 py-2.5 bg-gray-50 border-0 focus:ring-0 focus:outline-none"
              />
              {searchQuery && (
                <button
                  onClick={() => setSearchQuery('')}
                  className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
                >
                  <X className="h-4 w-4" />
                </button>
              )}
            </div>
          </div>
          <div className="p-2 max-h-[calc(100vh-300px)] overflow-y-auto">
            {filteredModels.map(model => (
              <div
                key={model.id}
                className={`flex items-center justify-between p-3 rounded-lg mb-1 cursor-pointer transition-all duration-200 ${selectedModel === model.id ? 'bg-blue-50 border-l-4 border-blue-500' : 'hover:bg-gray-100'}`}
                onClick={() => setSelectedModel(model.id)}
              >
                <div className="flex items-center">
                  <div className={`p-2 rounded-md mr-3 ${modelStatus[model.id] ? 'bg-blue-100 text-blue-600' : 'bg-gray-100 text-gray-400'}`}>
                    {model.icon}
                  </div>
                  <div>
                    <p className="text-sm font-medium text-gray-800">{model.name}</p>
                    <p className="text-xs text-gray-500">{modelStatus[model.id] ? '已启用' : '未启用'}</p>
                  </div>
                </div>
                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    toggleModelStatus(model.id);
                  }}
                  className={`p-1 rounded-full ${modelStatus[model.id] ? 'bg-green-100 text-green-600' : 'bg-gray-200 text-gray-500'}`}
                >
                  {modelStatus[model.id] ? (
                    <ToggleRight className="h-4 w-4" />
                  ) : (
                    <ToggleLeft className="h-4 w-4" />
                  )}
                </button>
              </div>
            ))}
          </div>
          <div className="p-4 border-t border-gray-200 bg-white flex justify-between items-center">
            <button className="text-sm text-blue-600 flex items-center hover:text-blue-800">
              <PlusCircle className="h-4 w-4 mr-1" />
              添加模型
            </button>
            <button className="text-sm text-gray-500 hover:text-gray-700">
              <HelpCircle className="h-4 w-4" />
            </button>
          </div>
        </div>

        {/* 右侧配置内容 */}
        <div className="flex-1 p-6">
          {renderModelConfig()}

          <div className="mt-6 flex justify-end">
            <button
              type="button"
              onClick={saveModelConfigs}
              className="inline-flex items-center px-4 py-2.5 border border-transparent rounded-lg shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
            >
              <Save className="mr-2 h-4 w-4" />
              保存配置
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

export default function SettingsPage() {
  const [activeSection, setActiveSection] = useState('global');
  const [imageSavePath, setImageSavePath] = useState('');
  const [isSaved, setIsSaved] = useState(false);
  const [isCheckingUpdate, setIsCheckingUpdate] = useState(false);
  const [updateStatus, setUpdateStatus] = useState<string>('');
  const [paddleOcrConfig, setPaddleOcrConfig] = useState({
    modelPath: './models',
    language: 'ch',
    enableAngleCls: true,
    useGpu: false,
    gpuId: 0,
    maxSideLen: 960,
    detDbThresh: 0.3,
    detDbBoxThresh: 0.6,
    detDbUnclipRatio: 1.5,
    recBatchNum: 6,
    recImgH: 48
  });

  // 从localStorage加载保存的配置
  useEffect(() => {
    const savedPath = localStorage.getItem('imageSavePath') || './moreocr_files';
    setImageSavePath(savedPath);
    
    const savedPaddleOcr = localStorage.getItem('paddleOcrConfig');
    if (savedPaddleOcr) {
      setPaddleOcrConfig(JSON.parse(savedPaddleOcr));
    }
  }, []);

  const handleSaveSettings = () => {
    // 保存到localStorage
    localStorage.setItem('imageSavePath', imageSavePath);
    localStorage.setItem('paddleOcrConfig', JSON.stringify(paddleOcrConfig));
    setIsSaved(true);
    
    // 3秒后隐藏保存成功提示
    setTimeout(() => {
      setIsSaved(false);
    }, 3000);
  };

  const handleCheckUpdate = async () => {
    setIsCheckingUpdate(true);
    setUpdateStatus('正在检查更新...');
    
    try {
      await updateService.checkForUpdates();
      setUpdateStatus('已是最新版本');
    } catch (error: any) {
      setUpdateStatus(error.message || '检查更新失败');
    } finally {
      setIsCheckingUpdate(false);
    }
  };

  const handleSelectFolder = async () => {
    try {
      const selected = await open({
        directory: true,
        multiple: false,
        title: '选择图片保存目录',
        defaultPath: imageSavePath && imageSavePath !== './moreocr_files' ? imageSavePath : undefined
      });
      
      if (selected) {
        setImageSavePath(selected as string);
      }
    } catch (error) {
      console.error('选择目录时出错:', error);
      alert('选择目录时出错，请确保选择有权限的目录');
    }
  };

  const handleSelectPaddleOcrFolder = async () => {
    try {
      const selected = await open({
        directory: true,
        multiple: false,
        title: '选择PaddleOCR模型目录'
      });
      
      if (selected) {
        setPaddleOcrConfig({...paddleOcrConfig, modelPath: selected as string});
      }
    } catch (error) {
      console.error('选择目录时出错:', error);
      alert('选择目录时出错，请确保选择有权限的目录');
    }
  };

  return (
    <div className="p-6 max-w-6xl mx-auto">
      <h1 className="text-2xl font-bold text-gray-800 mb-6">设置</h1>
      
      <div className="flex flex-col md:flex-row gap-6">
        {/* 侧边栏 */}
        <div className="md:w-64 flex-shrink-0">
          <div className="bg-white rounded-lg shadow-md p-4">
            <nav className="space-y-1">
              <button
              className={`w-full flex items-center px-4 py-3 text-left rounded-md transition-colors ${
                activeSection === 'global' 
                  ? 'bg-blue-50 text-blue-600 font-medium' 
                  : 'text-gray-700 hover:bg-gray-100'
              }`}
              onClick={() => setActiveSection('global')}
            >
              <Settings className="h-5 w-5 mr-3" />
              全局配置
            </button>
            <button
              className={`w-full flex items-center px-4 py-3 text-left rounded-md transition-colors ${
                activeSection === 'models' 
                  ? 'bg-blue-50 text-blue-600 font-medium' 
                  : 'text-gray-700 hover:bg-gray-100'
              }`}
              onClick={() => setActiveSection('models')}
            >
              <Cpu className="h-5 w-5 mr-3" />
              模型配置
            </button>
            <button
              className={`w-full flex items-center px-4 py-3 text-left rounded-md transition-colors ${
                activeSection === 'paddleocr' 
                  ? 'bg-blue-50 text-blue-600 font-medium' 
                  : 'text-gray-700 hover:bg-gray-100'
              }`}
              onClick={() => setActiveSection('paddleocr')}
            >
              <Info className="h-5 w-5 mr-3" />
              PaddleOCR配置
            </button>
            <button
              className={`w-full flex items-center px-4 py-3 text-left rounded-md transition-colors ${
                activeSection === 'about' 
                  ? 'bg-blue-50 text-blue-600 font-medium' 
                  : 'text-gray-700 hover:bg-gray-100'
              }`}
              onClick={() => setActiveSection('about')}
            >
              <Info className="h-5 w-5 mr-3" />
              关于
            </button>
            </nav>
          </div>
        </div>
        
        {/* 主内容区 */}
        <div className="flex-1">
          {/* 全局配置 */}
          {activeSection === 'global' && (
            <div className="bg-white rounded-lg shadow-md p-6">
              <h2 className="text-lg font-semibold text-gray-800 mb-4">全局配置</h2>
              
              <div className="space-y-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    图片保存路径
                  </label>
                  <div className="flex">
                    <input
                      type="text"
                      value={imageSavePath}
                      onChange={(e) => setImageSavePath(e.target.value)}
                      placeholder="请选择图片保存路径"
                      className="flex-1 min-w-0 block w-full px-3 py-2 rounded-l-md border border-gray-300 shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
                    />
                    <button
                      type="button"
                      onClick={handleSelectFolder}
                      className="inline-flex items-center px-3 py-2 border border-l-0 border-gray-300 rounded-r-md shadow-sm text-sm font-medium text-gray-700 bg-gray-50 hover:bg-gray-100 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                    >
                      <Folder className="h-4 w-4 text-gray-500" />
                    </button>
                  </div>
                  <p className="mt-2 text-sm text-gray-500">
                    上传的图片将保存到此路径下
                  </p>
                </div>
              </div>
              
              <div className="mt-6 flex justify-end">
                <button
                  type="button"
                  onClick={handleSaveSettings}
                  className="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                >
                  <Save className="mr-2 h-4 w-4" />
                  保存设置
                </button>
              </div>
            </div>
          )}
          
          {/* 模型配置 */}
          {activeSection === 'models' && (
            <ModelConfigSection />
          )}
          
          {/* PaddleOCR配置 */}
          {activeSection === 'paddleocr' && (
            <div className="bg-white rounded-lg shadow-md p-6">
              <h2 className="text-lg font-semibold text-gray-800 mb-4">PaddleOCR 配置</h2>
              
              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">模型路径</label>
                  <div className="flex">
                    <input
                      type="text"
                      value={paddleOcrConfig.modelPath}
                      onChange={(e) => setPaddleOcrConfig({...paddleOcrConfig, modelPath: e.target.value})}
                      className="flex-1 min-w-0 block w-full px-3 py-2 rounded-l-md border border-gray-300 shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
                      placeholder="./models/paddleocr"
                    />
                    <button
                      type="button"
                      onClick={handleSelectPaddleOcrFolder}
                      className="inline-flex items-center px-3 py-2 border border-l-0 border-gray-300 rounded-r-md shadow-sm text-sm font-medium text-gray-700 bg-gray-50 hover:bg-gray-100 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                    >
                      <Folder className="h-4 w-4 text-gray-500" />
                    </button>
                  </div>
                  <p className="mt-1 text-xs text-gray-500">PaddleOCR模型文件所在路径</p>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">识别语言</label>
                  <select
                    value={paddleOcrConfig.language}
                    onChange={(e) => setPaddleOcrConfig({...paddleOcrConfig, language: e.target.value})}
                    className="w-full px-3 py-2.5 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  >
                    <option value="ch">中文</option>
                    <option value="en">英文</option>
                    <option value="chinese_cht">繁体中文</option>
                    <option value="japan">日文</option>
                    <option value="korean">韩文</option>
                    <option value="ml">多语言</option>
                  </select>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">最大边长</label>
                    <input
                      type="number"
                      value={paddleOcrConfig.maxSideLen}
                      onChange={(e) => setPaddleOcrConfig({...paddleOcrConfig, maxSideLen: parseInt(e.target.value)})}
                      className="w-full px-3 py-2.5 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      min="256"
                      max="4096"
                    />
                    <p className="mt-1 text-xs text-gray-500">像素</p>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">置信度阈值</label>
                    <input
                      type="number"
                      value={paddleOcrConfig.detDbThresh}
                      onChange={(e) => setPaddleOcrConfig({...paddleOcrConfig, detDbThresh: parseFloat(e.target.value)})}
                      className="w-full px-3 py-2.5 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      min="0.1"
                      max="1.0"
                      step="0.1"
                    />
                  </div>
                </div>

                <div className="space-y-2">
                  <label className="flex items-center">
                    <input
                      type="checkbox"
                      checked={paddleOcrConfig.enableAngleCls}
                      onChange={(e) => setPaddleOcrConfig({...paddleOcrConfig, enableAngleCls: e.target.checked})}
                      className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                    />
                    <span className="ml-2 text-sm text-gray-700">启用角度分类</span>
                  </label>

                  <label className="flex items-center">
                    <input
                      type="checkbox"
                      checked={paddleOcrConfig.useGpu}
                      onChange={(e) => setPaddleOcrConfig({...paddleOcrConfig, useGpu: e.target.checked})}
                      className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                    />
                    <span className="ml-2 text-sm text-gray-700">使用GPU加速</span>
                  </label>
                </div>

                {paddleOcrConfig.useGpu && (
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">GPU设备ID</label>
                    <input
                      type="number"
                      value={paddleOcrConfig.gpuId}
                      onChange={(e) => setPaddleOcrConfig({...paddleOcrConfig, gpuId: parseInt(e.target.value)})}
                      className="w-full px-3 py-2.5 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      min="0"
                      max="7"
                    />
                  </div>
                )}
              </div>
              
              <div className="mt-6 flex justify-end">
                <button
                  type="button"
                  onClick={handleSaveSettings}
                  className="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                >
                  <Save className="mr-2 h-4 w-4" />
                  保存设置
                </button>
              </div>
            </div>
          )}

          {/* 关于 */}
          {activeSection === 'about' && (
            <div className="bg-white rounded-lg shadow-md p-6">
              <h2 className="text-lg font-semibold text-gray-800 mb-4">关于</h2>
              
              <div className="space-y-4">
                <div className="flex items-center">
                  <div className="bg-blue-100 p-3 rounded-lg mr-4">
                    <Info className="h-8 w-8 text-blue-600" />
                  </div>
                  <div>
                    <h3 className="text-xl font-medium text-gray-900">MoreOCR</h3>
                    <p className="text-gray-500">版本 0.1.0</p>
                  </div>
                </div>
                
                <div className="border-t border-gray-200 pt-4">
                  <h4 className="font-medium text-gray-900 mb-2">作者</h4>
                  <p className="text-gray-600">MoreOCR 开发团队</p>
                </div>
                
                <div className="border-t border-gray-200 pt-4">
                  <h4 className="font-medium text-gray-900 mb-2">描述</h4>
                  <p className="text-gray-600">
                    MoreOCR 是一个基于 Web 的 OCR（光学字符识别）应用，
                    旨在为用户提供文档图像中文字提取的解决方案。
                  </p>
                </div>

                <div className="border-t border-gray-200 pt-4">
                  <h4 className="font-medium text-gray-900 mb-2">软件更新</h4>
                  <div className="flex items-center space-x-4">
                    <button
                      type="button"
                      onClick={handleCheckUpdate}
                      disabled={isCheckingUpdate}
                      className="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50"
                    >
                      {isCheckingUpdate ? (
                        <>
                          <RefreshCw className="mr-2 h-4 w-4 animate-spin" />
                          检查中...
                        </>
                      ) : (
                        <>
                          <Download className="mr-2 h-4 w-4" />
                          检查更新
                        </>
                      )}
                    </button>
                    {updateStatus && (
                      <p className="text-sm text-gray-600">{updateStatus}</p>
                    )}
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
      
      {isSaved && (
        <div className="fixed bottom-4 right-4 flex items-center px-4 py-2 bg-green-500 text-white rounded-md shadow-lg">
          <CheckCircle className="h-4 w-4 mr-2" />
          设置已保存
        </div>
      )}
    </div>
  );
}